<template>
  <section>
    <!-- 引入公共组件 BaseInfo -->
    <div class="base-info-title">
      <div class="title-line"></div>
      基本信息
    </div>
    <ul class="user-info">
      <li>{{ patientInfo.realName }}</li>
      <li>
        <img src="@/assets/images/id-icon.png" alt="" />
        ID：{{ patientInfo.code }}
      </li>
      <li>
        <img src="@/assets/images/sex-icon.png" alt="" />
        性别：{{
          patientInfo.sex == "2" ? "--" : patientInfo.sex == "0" ? "男" : "女"
        }}
      </li>
      <li>
        <img src="@/assets/images/patient-icon.png" alt="" />
        家族遗传史：{{
          patientInfo.familyHistory ? patientInfo.familyHistory : "无"
        }}
      </li>
      <li>
        <img src="@/assets/images/address-icon.png" alt="" />
        地区：{{ patientInfo.address.length ? patientInfo.address : "无" }}
      </li>
    </ul>
    <div class="user-table">
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        id="user-table-1"
        :highlight-current-row="true"
        :style="{height: warpHeight + 'px'}"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="count" label="筛选" width="auto" align="center">
        </el-table-column>
        <el-table-column
          sortable
          prop="createTime"
          label="日期"
          width="auto"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="result" label="结果" width="auto" align="center">
        </el-table-column>
        <el-table-column prop="" label="筛选报告" align="center">
          <template slot-scope="scope">
            <!-- <img class="result-icon" :src="(scope.$index%2)?resultIcon.icon1:resultIcon.icon2" @click="seeResult(scope.$index, scope.row)"> -->
            <img
              class="result-icon"
              :src="resultIcon.icon2"
              @click="seeResult(scope.$index, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="load-more">
        <el-button
          class="btn-hover"
          style="
            padding: 10px 26px;
            font-size: 14px;
            background-color: #8775ff;
            border-radius: 4px;
            flex: none;
            cursor: pointer;
            color: #fff
          "
           @click="loadMore"
          >{{noMore ? '收起' : '展开'}}</el-button
        >
      </div>
    </div>

    <div class="check-result-btns">
      <div class="btn-bg btn" @click="patientInfoExport">导出</div>
    </div>
    <div class="check-all"></div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="异常指标" name="first">
        <Result-Item :resultTitle="resultTitle">
          <template>
            <ul v-if="resultJsonArray[checkCount]" class="anomaly-introduce">
              <li
                v-for="(item, index) in resultJsonArray[checkCount]"
                :key="index"
              >
                <span class="order">{{ index + 1 }}</span
                >&nbsp;&nbsp; {{ item.name }}值：<span class="num-color">{{
                  item.value
                }}</span
                >，正常范围{{ item.normalRange }}，<span class="num-color">{{
                  item.result
                }}</span>
              </li>
            </ul>
            <ul v-else style="line-height: none">
              <li>无</li>
            </ul>
          </template>
        </Result-Item>
      </el-tab-pane>
      <el-tab-pane label="疾病预测" name="second">
        <Result-Item :resultTitle="resultTitle">
          <template v-if="resultExplainArray[checkCount]">
            <ul
              class="disease-prediction"
              v-for="(item, index) in resultExplainArray[checkCount]"
              :key="index"
            >
              <li>
                <span class="title"
                  ><span class="order">{{ index + 1 }}</span
                  >.&nbsp;&nbsp;{{ item.ill }}</span
                >
              </li>
              <li class="line-text--one">
                <span class="title">相关异常指标：</span>
                <span class="derivation">
                  {{ item.name }}
                  <span
                    class="source"
                    @click="copyTemplate('解析来源于', item.sourceData)"
                    >解析来源于</span
                  >
                  <el-popover
                    v-if="item.sourceData.length > 80"
                    placement="top-start"
                    title="解析来源于"
                    width="800"
                    trigger="hover"
                    :content="item.sourceData"
                  >
                    <span slot="reference" class="source-content">
                      {{ item.sourceData }}
                    </span>
                  </el-popover>

                  <span v-else slot="reference" class="source-content">
                    {{ item.sourceData }}
                  </span>
                </span>
              </li>
              <!-- <el-popover placement="top-start" title="异常解析：" width="800" trigger="hover" :content="item.abnormalityCause"> -->
              <li slot="reference">
                <span
                  class="title"
                  @click="copyTemplate('异常解析：', item.abnormalityCause)"
                  >异常解析：</span
                >
                {{ item.abnormalityCause }}
              </li>
              <!-- </el-popover> -->
              <!-- <el-popover placement="top-start" title="临床表现：" width="800" trigger="hover" :content="item.manifestation"> -->
              <li slot="reference">
                <span
                  class="title"
                  @click="copyTemplate('临床表现：', item.manifestation)"
                >
                  临床表现：</span
                >
                {{ item.manifestation }}
              </li>
              <!-- </el-popover> -->

              <!-- <li>
                            <span class="title">经典型：</span>
                            等数据……
                        </li> -->
            </ul>
          </template>
          <template v-else>
            <ul style="line-height: none">
              <li>无</li>
            </ul>
          </template>
        </Result-Item>
      </el-tab-pane>
    </el-tabs>
  </section>
</template>

<script>
import ResultItem from "@/views/dashboard/ResultItem";
import { patientInfoById, patientInfoExport } from "@/api/customer";

import { exportMethod } from "@/utils/exportMethod";
export default {
  components: {
    ResultItem,
  },

  created() {
    this.patientInfoById();
  },

  data() {
    return {
      counts: 2,
      warpHeight: 0,
      totalData: 0,
      // 编号
      serialCode: "",
      activeName: "first",
      resultTitle: "异常指标", //tab切换
      recordId: "", //	筛查记录id
      hasIll: false, //指标异常标识 true，false 无异常
      patientInfo: {
        //患者详情信息
        customerId: "",
        realName: "",
        code: "",
        sex: "",
        familyHistory: "",
        address: "",
      },
      resultIcon: {
        //报告图标
        icon1: require("@/assets/images/result-icon-1.png"),
        icon2: require("@/assets/images/result-icon-2.png"),
      },
      tableData: [], //表格数据
      resultJsonArray: [], //指数分析
      resultExplainArray: [], //疾病预测分析
      checkCount: 0, //查看检查报告索引
      sysCustomerRecords: [], //所有报告数据
      loadCount: 2, // 加载条数
    };
  },

  watch: {},
  computed: {
    noMore () {
      return this.tableData.length === this.counts
    },
  },
  methods: {
    loadingState(text) {
      return this.$loading({
        lock: true,
        text: text,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
    },
    // 加载更多
    loadMore() {
    if (this.counts < this.totalData.length) {
      this.counts+=10
      if (this.counts > this.totalData.length) {
        this.counts = this.totalData.length
      }
    } else if (this.noMore){
     this.counts = 2
        let top = document.querySelector(".load-more").offsetTop
        let section = document.querySelector(".app-main"); //document.querySelector(".load-more").offsetTop
        section.scrollTop =  200;
        console.log(top, section.scrollTop);
    
    }
       this.patientInfoById()
    },
    handleClick(tab, event) {
      console.log(tab, event);

      console.log("lable===============", tab.label);

      this.resultTitle = tab.label;
    },

    /**
     * 切换 查看结果报告
     */
    seeResult(line, row) {
      this.$nextTick(() => {
        let section = document.querySelector(".app-main");
        section.scrollTop = document.querySelector(".check-all").offsetTop - 60;
      });
      console.log("表格信息", line, row);
      this.checkCount = line;
      this.recordId = this.sysCustomerRecords[line].recordId;
    },

    /**
     * 查看单个患者信息
     */
    sortDataArray(dataArray) {
      return dataArray.sort(function (a, b) {
        return b.sort - a.sort;
        // return Date.parse(b.date.replace(/-/g,"/"))-Date.parse(a.date.replace(/-/g,"/"));
      });
    },
    async patientInfoById() {
      this.loadingState('加载中')
      const res = await patientInfoById(this.$route.query.customerId);
      console.log("查看单个患者信息", res);

      if (res.code != 200) return;
      this.patientInfo = {
        ...res.sysCustomer,
      };
      this.sysCustomerRecords = res.sysCustomerRecords;
      this.recordId = res.sysCustomerRecords[0].recordId;
      this.serialCode = res.sysCustomer.code;

      // 赋值表格数据
      let tableData = res.sysCustomerRecords.map((item, i) => ({
        sort: i,
        count: item.count,
        createTime: item.createTime.substring(0, 10),
        result: item.result ? item.result : "--",
      }));
      this.totalData = tableData
      // this.tableData = this.sortDataArray(tableData).slice(0, this.loadCount);
      this.tableData = tableData

     this.$nextTick(() => {
       let offsetHeight = document.querySelector('.el-table__row').offsetHeight
       this.warpHeight = offsetHeight * this.counts + 59
        console.log(this.warpHeight);
        if (tableData.length < 2) {
          this.warpHeight = offsetHeight + 59
        }
     })
      // 处理异常指标详情
      res.sysCustomerRecords.forEach((obj) => {
        let resultArr = [];
        let explainArr = [];
        if (obj.abnormalIndex.length) {
          obj.abnormalIndex.forEach((obj1) => {
            if (obj1.resultJsonArray.length) {
              obj1.resultJsonArray.forEach((obj2) => {
                // 判断是否有重复
                if (
                  !resultArr.filter((item) => item.nameEn == obj2.nameEn).length
                ) {
                  resultArr.push(obj2);
                }
              });
            }
          });
        }

        if (obj.resultExplain.length) {
          obj.resultExplain.forEach((obj1) => {
            // 判断是否有重复
            if (!explainArr.filter((item) => item.ill == obj1.ill).length) {
              explainArr.push(obj1);
            }
          });
        }

        this.resultJsonArray.push(resultArr);
        this.resultExplainArray.push(explainArr);
      });
      this.loadingState().close()
      // console.log('处理异常指标详情', this.resultJsonArray);
      // console.log('处理异常指标详情', (this.resultJsonArray[this.checkCount]).length, Object.prototype.toString.apply(this.resultJsonArray[this.checkCount]));
      // console.log('处理异常指标详情详情', this.resultExplainArray);
    },

    /**
     * 导出
     */
    async patientInfoExport() {
      const res = await patientInfoExport(this.recordId, this.serialCode);
      // console.log(res, res.msg);
      // this.$message.warning(res.msg)
    },

    // 复制模板内容
    copyTemplate(tips, value) {
      this.copyToClipboard(value); // 需要复制的文本内容
      this.$message.success(tips + "复制成功");
    },
    // 点击复制到剪贴板函数
    copyToClipboard(content) {
      //window.clipboardData的作用是在页面上将需要的东西复制到剪贴板上，
      //提供了对于预定义的剪贴板格式的访问，以便在编辑操作中使用。
      if (window.clipboardData) {
        /*
          window.clipboardData有三个方法:
        setData(sDataFormat, sData) 给剪贴板赋予指定格式的数据。返回 true 表示操作成功。
          */
        window.clipboardData.setData("text", content);
      } else {
        (function (content) {
          //oncopy 事件在用户拷贝元素上的内容时触发。
          document.oncopy = function (e) {
            e.clipboardData.setData("text", content);
            e.preventDefault(); //取消事件的默认动作
            document.oncopy = null;
          };
        })(content);
        //execCommand方法是执行一个对当前文档/当前选择/给出范围的命令。
        //'Copy':将当前选中区复制到剪贴板。
        document.execCommand("Copy");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.load-more {
  width: 100px;
  margin: auto;
}
.base-info-title {
  font-size: 16px;
  color: #3c3978;
  font-weight: bold;
  display: flex;
  align-items: center;
  height: fit-content;
  background: #fff;
  padding: 20px 30px;

  .title-line {
    width: 3px;
    height: 14px;
    background-color: #e984ca;
    border-radius: 1px;
    margin-right: 6px;
    margin-top: -4px;
  }
}

.user-info {
  display: flex;
  background-image: linear-gradient(#8775ff, #8775ff),
    linear-gradient(#ffffff, #ffffff);
  padding: 18px 30px;

  li {
    margin-right: 40px;
    flex-shrink: 0;
    font-size: 16px;
    color: #fff;
    display: flex;

    img {
      width: 16px;
      height: 16px;
      margin-right: 5px;
    }
  }
}

.el-tabs {
  background: #fff;
}

.user-table {
  padding: 40px 30px;
  background: #fff;

  .result-icon {
    width: 18px;
    height: 20px;
    cursor: pointer;
  }

  .el-table--border {
    border-radius: 4px;
  }

  .el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell {
    background-color: red !important;
  }
}
</style>
<style lang="scss"></style>
